package com.skyworthclub.competition.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.skyworthclub.competition.beans.Feedback;
import com.skyworthclub.competition.beans.User;
import com.skyworthclub.competition.mapper.FeedbackMapper;
import com.skyworthclub.competition.service.FeedbackService;
import com.skyworthclub.competition.service.UserService;
import com.skyworthclub.competition.utils.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author li
 * @since 2018-10-15
 */
@EnableAsync
@Service
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, Feedback> implements FeedbackService {
    private final EmailService emailService;
    private static final Integer PAGE_SIZE = 10;
    private final UserService userService;

    @Autowired
    public FeedbackServiceImpl(EmailService emailService, UserService userService) {
        this.emailService = emailService;
        this.userService = userService;
    }

    /** 保存反馈并邮件通知管理员
     * @param feedback  反馈对象实例
     */
    @Override
    public boolean insertAndNotice(Feedback feedback) {
        feedback.setFeedbackTime(LocalDateTime.now());
        emailService.feedbackNotice(feedback.getFeedbackContent());
        return super.insert(feedback);
    }

    @Override
    public Page<Feedback> selectUserFeedbackPage(String username, Integer pageNum) {
        EntityWrapper<User> uWrapper = new EntityWrapper<>();
        uWrapper.eq("username", username);
        User user = userService.selectOne(uWrapper);
        EntityWrapper<Feedback> fWrapper = new EntityWrapper<>();
        fWrapper.eq("feedback_user_id", user.getId());
        fWrapper.orderBy("feedback_id", false);
        Page<Feedback> page = new Page<>(pageNum, PAGE_SIZE);
        return super.selectPage(page, fWrapper);
    }

    @Override
    public Page<Feedback> selectFeedbackPage(Integer pageNum) {
        Page<Feedback> page = new Page<>(pageNum, PAGE_SIZE);
        EntityWrapper<Feedback> wrapper = new EntityWrapper<>();
        wrapper.orderBy("feedback_id", false);
        return super.selectPage(page, wrapper);
    }
}
